include('shared.lua')

---------------------------------------------
-- Entity Functions
---------------------------------------------

function ENT:Initialize()
	self.Entity:SetModel("models/props_lab/reciever01b.mdl")
	self.Entity:PhysicsInit( SOLID_VPHYSICS )
	self.Entity:SetMoveType(MOVETYPE_VPHYSICS)
	self.Entity:SetSolid(SOLID_VPHYSICS)
	self.Entity:SetUseType(SIMPLE_USE)
	
	self.code = 0
	self.autoclose = false
	self.didclose = false  --We don't want to keep closing the gate after the iris code was sent
end

function ENT:SpawnFunction( ply, tr)
	local SpawnPos = tr.HitPos + tr.HitNormal * 50
	local ent = ents.Create( "iris_computer" )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()
	return ent
end

function ENT:Use(ply)
	local ac = 0 
	if self.autoclose then
		ac = 1
	end
	ply:ConCommand("showirismenu " .. self.code .. " " .. ac)
	ply.IrisCompEnt=self
	Msg(self.code .. " " .. tostring(self.autoclose) .."\n")
end

function ENT:Think()
	gate = self:FindGate()
	if gate then
		if gate:GetOwner() == self:GetOwner() then
			if not gate.outbound and (gate.open or gate.inuse) then
				if self.autoclose and not self.didclose then
					if not gate.irisclosed then
						gate:OpenIris(false)
						self.didclose = true --We won't close the iris again until then next time the gate is active
					end
				end
			end
		end
			
		if not (gate.open or gate.inuse) and self.didclose then
			self.didclose = false  --Resetting so we can autoclose again
			gate:OpenIris(true)
		end
	end
	self.Entity:NextThink(CurTime()+0.5)
	return true
end

---------------------------------------------
-- Server/Client crossover stuff
---------------------------------------------

function ChangeIrisSettings(player, command, args)
	if player.IrisCompEnt and player.IrisCompEnt ~= NULL then
		player.IrisCompEnt.code = tonumber(args[1])
		if args[2] == "1" then
			player.IrisCompEnt.autoclose = true
		else
			player.IrisCompEnt.autoclose = false
		end
		player.IrisCompEnt = nil
	end
end

concommand.Add("changeirissettings", ChangeIrisSettings)

---------------------------------------------
-- Gate Stuff
---------------------------------------------

function ENT:FindGate() --modified from avon's dhd function
	local nearest
	local gateDist = 500 -- max distance to gate
	local sg = {}
	for _,v in pairs(ents.FindByClass("stargate_sg1")) do
		table.insert(sg,v)
	end
	for _,v in pairs(ents.FindByClass("stargate_atlantis")) do
		table.insert(sg,v)
	end
	for _,v in pairs(sg) do
		local sg_dist = (self.Entity:GetPos() - v:GetPos()):Length()
		if(gateDist >= sg_dist) then
			gateDist = sg_dist
			nearest = v
		end
	end
	--nearest:SetPowerRessource(self.Entity)
	return nearest
end

function ENT:RecieveIrisCode(code)
	gate = self.FindGate()
	if code == self.code then
		if gate.irisclosed then
			gate.OpenIris(true)
		end
	end
end